#!/usr/bin/python 

import sys

def read_and_count(filename):
  words_map={}
  file=open(filename, 'r')
  for str in file:
    arr=str.split()
    for s in arr:
      s=s.lower();
      if s not in words_map:
        words_map[s] = 1
      else:
        words_map[s] +=1
  file.close() 
  return words_map
# 
def print_words(filename):
  words_map=read_and_count(filename)
  keys=sorted(words_map.keys())
  for key in keys:
    print key, words_map[key]
  return
#
def get_count(word):
  return word[1]

def print_top(filename):
  words_map = read_and_count(filename)
  items = sorted(words_map.items(), key=get_count, reverse=True)
  for i in items[:20]:
    print i[0], i[1]


def main():
  if len(sys.argv) != 3:
    print 'usage: ./wordcount.py {--count | --topcount} file'    
    sys.exit(1)

  option = sys.argv[1]
  filename = sys.argv[2]
  if option == '--count':
    print_words(filename)
  elif option == '--topcount':
    print_top(filename)
  else:
    print 'unknown option: ' + option
    sys.exit(1)

if __name__ == '__main__':
  main()
